/**
 * Created by Administrator on 2016/12/17.
 */
/**
 * Created by Administrator on 2016/12/16.
 */
$(function () {
    init();
    uploadImg();
    $('input[type="text"]').attr('readonly', "readonly");
    $('.addWorkers,.dealAll,.remove,.cancel,.resure').addClass("disabled");

}),
/*********点编辑按钮实现可操作功能************/
    $('.edit-style').click(function () {
        $('input[type="text"]').removeAttr('readonly');
        this.style.display = 'none';
        $('.addWorkers,.dealAll,.remove,.cancel,.resure').removeClass("disabled");
    });
/*********日期***********/
$(".form-date").datetimepicker(
    {
        language: "zh-CN",
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        minView: 2,
        forceParse: 0,
        format: "yyyy-mm-dd"
    });
/***弹出工地数据管理页面***/
$('.tab2Content2').click(function () {
    layer.open({
        title: '工地数据管理',
        shadeClose: true,
        shade: 0.8,
        type: 2,
        fix: false,
        maxmin: true,
        area: ['100%', '100%'],
        content: '../../../../siteData/siteDate.html'
    })
});
/*********弹出班组资金管理页面************/
$('.tab2Content3').click(function () {
    layer.open({
        title: '班组资金管理',
        shadeClose: true,
        shade: 0.8,
        type: 2,
        fix: false,
        maxmin: true,
        area: ['100%', '100%'],
        content: '../../edit/projectDetailsEdit/projectEdit.html'
    })
});
/*************弹出项目资金管理页面**************/
$('.tab2Content4').click(function () {
    layer.open({
        title: '项目资金管理',
        shadeClose: true,
        shade: 0.8,
        type: 2,
        fix: false,
        maxmin: true,
        area: ['100%', '100%'],
        content: '../../edit/projectDetailsEdit/projectEdit.html'
    })
});

/*******接收projectView班组列表信息页发送的数据 ，并将些信息同步在班组详情页上 ************/
var str = location.search;
var json = {};
str = str.slice(1).split("&");
//console.log(str);
for (var i = 0; i < str.length; i++) {
    var result = str[i].split("=");
    json[result[0]] = result[1];
}
console.log(json);
$.ajax({
    type: 'put',
    url: `http://192.168.59.3:8082/console/projectInfo/teamDetail/${json.teamId}`,
    contentType: "application/json",
    success: function (data) {
        // console.log(data);
        $("[data-name]").each(function (i, e) {
            $(e).val(data.data[$(e).attr('data-name')]);
        })
    },
    error: function (err) {
        //console.log(err);
    }

});
///////////////////////////////////////
/*********加载分包班组成员信息表***********/

function init() {
    //$("#teamDetailTable").data("bootstrap.table").options.url="http://192.168.59.3:8082/console/projectInfo/findWorkerByTeam/"+json.teamId+"/1/10";
    $("#teamDetailTable").bootstrapTable({
        method: 'get',
        url: `http://192.168.59.3:8082/console/projectInfo/findWorkerByTeam/${json.teamId}`,
        onLoadSuccess: function (data) {
            // console.log(data);
            $('.bs-checkbox').hide();
        }
    });
}
function responseHandler(res) {
    var needData = {
        rows: res.data.list,
        total: res.data.total
    }
    return needData;
}
function teamTableQuery(params) {
    params['pageNum'] = (params.offset / params.limit) + 1;
    params.pageSize = params.limit;
    return params;
}
function sexFmt(index, val, row) {
    return (val.sex == 0) ? '女' : '男';
}
/*function removeFmt(index,val,row){
    return `<button class="btn btn-danger">删除</button>`;
}*/
/********点击批量删除显示表格的全选按钮**********/
var state = false;
$('.dealAll').click(function () {
    if (!state) {
        $('.bs-checkbox').show();
        state = true;
    } else {
        $('.bs-checkbox').hide();
        state = false;
    }
});


$('input[data-name="teamTypeName"]').focus(function(){
    var teamTypeInfo=JSON.parse(sessionStorage.getItem("teamTypeInfo"));
    console.log(teamTypeInfo);
    $.ajax({
        type:'get',
        url:`http://192.168.59.3:8082/console/teamTypeInfo/getTeamTypeInfoList?pageNum=1&pageSize=10`,
        // data:JSON.stringify({"pageNum":1,"pageSize":10,}),
        contentType:'application/json',
        success:function(data){
            console.log(JSON.parse(data).data);
            // localStorage.contractor=data;

            var arr=JSON.parse(data).data;
            var str="";
            for(var i=0;i<arr.length;i++){
                for(var key in arr[i]){
                    str+="&"+key+"="+arr[i][key]
                }
            }
            console.log(str);
            layer.open({
                title:"分包班组承包人列表",
                type:2,
                area:['50%','50%'],
                maxmin:true,
                fix:false,
                shadeClose:true,
                content:`../../../addDetails/addTeams/teamType/teamType.html?${str.slice(1)}`
            })
        },
        error:function(err){
            console.log(err);
        }
    });
});
$('input[data-name="teamTypeName"]').blur(function(){
    var moved = 0;
    var timer = setInterval(function () {
        moved++;
        var teamTypeInfo=JSON.parse(sessionStorage.getItem("teamTypeInfo"));
        // console.log(teamTypeInfo);
        if (teamTypeInfo.teamTypeName||teamTypeInfo.teamTypeName!=this.value) {
            this.value = teamTypeInfo.teamTypeName;
            clearInterval(timer);
            timer = null;
            //sessionStorage.clear("teamTypeInfo");
        }
        if (moved >= 3) {
            clearInterval(timer);
            timer = null;
        }
    }.bind(this), 100)

})

/***********点击新增工人 按钮，并发送数据 ，弹出新增工人页面窗口******************/

$('.addWorkers').click(function(){
    console.log(111);
    $.ajax({
        type:"post",
        url:`http://192.168.59.3:8082/console/projectInfo/findUserListByRole`,
        data:'{"pageNum":1,"pageSize":10,"roleId":1}',
        contentType:'application/json',
        success:function(data){
            console.log(JSON.parse(data));
            localStorage.contractor=data;
        },
        error:function(err){
            console.log(err);
        }
    });
    layer.open({
        title: '选择建筑工人',
        shadeClose: true,
        shade: 0.8,
        type: 2,
        fix: false,
        maxmin: true,
        area: ['50%', '50%'],
        content: `../../../addDetails/addWorkers/addWorkers.html?projectCode=${json.projectCode}&teamId=${json.teamId}`,
        end:function(){
            $("#teamDetailTable").bootstrapTable("refresh",`http://192.168.59.3:8082/console/projectInfo/findWorkerByTeam/${json.teamId}`)
        }
    })
});
// 上传图片
function uploadImg() {
    var url = "http://192.168.59.2:7090/image";
    var firstName = "http://choosefine-uat.oss-cn-hangzhou.aliyuncs.com/";
    if ($('[data-pic]')) {
        $('[data-pic]')
            .html(`
            <img src="#">
            <form action=${url} method="post" enctype="multipart/form-data" target="hide_frame" style="display: none;">
              <input name="name">
              <input type="file" name="file"/>
            <form>
          `)
            .find('[type="file"]').on('change',
            function () {
                var lastName = "console/user/" + (new Date()).getTime() + '-' + this.files[0].name;
                $(this).prev().val(lastName);
                $(this).parent().submit();
                console.log(firstName + lastName);
                var timer = setTimeout(function () {
                    $(this).parent().prev().attr('src', firstName + lastName);
                }.bind(this), 12000)
            });
        $('[data-pic]').each(function (i, div) {
            var dataName = $(div).attr('data-pic');
            $(div).find('img').attr('data-name', dataName)
        });
        $('[data-pic]').find('img').click(function () {
            $(this).parent().find('[type="file"]').click();
        });
        $(document.body).append(`
            <iframe name="hide_frame" style="display: none">
          `)
    }
}
/***********点击按钮实现不同功能，点击删除则删除所选中数据***************/
$('.fixed-table-footer').on("click","button",function(e){
    var rId=$('.selected td:eq(1)').text();console.log(rId);

    if(this.innerHTML=="确定修改"){//当点击 完工的时候提交数据
        var oIpt = $('[data-name]');
        console.log(oIpt);
        var str = {};
        for (var i = 0; i < oIpt.length; i++) {
            //console.log(($(oIpt[i]).attr('data-name')));
            if (oIpt[i].nodeName == "INPUT") {
                str[$(oIpt[i]).attr('data-name')] = $(oIpt[i]).val();
            };
            //console.log($(oIpt[i]).attr("data-name") == "contractorAuthorization");

            if ($(oIpt[i]).attr("data-name") == "contractorAuthorization") {
                var oA="";
                var a1=$(oIpt[i]).find("input[type='file']");
                console.log(a1);
                a1.each(function(i,e){
                    if(e.files[0]){
                        console.log(e.files[0].name);
                        oA+="imgs/"+e.files[0].name+",";
                    }
                })
                oA = oA.slice(0,oA.length-1);
                console.log(oA);
            }
        }
        str['projectStart'] = new Date(str.projectStart).getTime();
        str["projectCode"]=json.projectCode;
        str["teamId"]=json.teamId;
        console.log(JSON.stringify(str));
        //多个项目ID之间用逗号分隔
        $.ajax({
            type:'post',
            contentType:"application/json",
            url:`http://192.168.59.3:8082/console/projectInfo/updateTeam`,
            data:JSON.stringify(str),
            success:function(data){
                console.log(data);
                //console.log($('.selected tr:eq(8)'));
                parent.layer.closeAll();
            },
            error:function(err){
                console.log(err);
            }
        });

    };
    if(this.innerHTML=="删除"){//当点击删除的时候提交数据到后删除数据
        console.log(222);
        //var oPid =$("#teamTable").data('bootstrap.table').options.data;
        $.ajax({
            type:'put',
            contentType:"application/json",
            url:`http://192.168.59.3:8082/console/projectInfo/deleteWorkerItemsRelation/${rId}`,
            data:'{"relationId":rId}',
            success:function(data){
                console.log(data);
            },
            error:function(err){
                console.log(err);
            }
        });
        $('.selected').remove();
    }
})




